package com.keldian.www.xmppdemo;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.*;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jivesoftware.smack.packet.*;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

    private EditText edtLoginID, edtPwd, edtFriendID, edtTextMsg;

    private EditText mEt_username;
    private EditText mEt_password;
    private Button mBtn_connect;
    private Button mBtn_register;
    private Button mBtn_login;

    private Button btn_AddFriend, btn_sendText, btn_sendImg, btn_sendVideo;


    private XMPPTCPConnection mXMPPTCPConnection;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(getApplicationContext(), msg.obj + "", Toast.LENGTH_LONG).show();
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    private void initView() {
        mEt_username = (EditText) findViewById(R.id.et_username);
        mEt_password = (EditText) findViewById(R.id.et_password);
        mBtn_connect = (Button) findViewById(R.id.btn_connect);
        mBtn_register = (Button) findViewById(R.id.btn_register);
        mBtn_login = (Button) findViewById(R.id.btn_login);

        btn_AddFriend = (Button) findViewById(R.id.btn_AddFriend);
        btn_sendText = (Button) findViewById(R.id.btn_sendText);

        btn_sendImg = (Button) findViewById(R.id.btn_sendImg);
        btn_sendVideo = (Button) findViewById(R.id.btn_sendVideo);

        edtFriendID = (EditText) findViewById(R.id.edtFriendID);
        edtTextMsg = (EditText) findViewById(R.id.edtTextMsg);

        mBtn_connect.setOnClickListener(this);
        mBtn_register.setOnClickListener(this);
        mBtn_login.setOnClickListener(this);
        btn_AddFriend.setOnClickListener(this);
        btn_sendText.setOnClickListener(this);

        btn_sendImg.setOnClickListener(this);
        btn_sendVideo.setOnClickListener(this);
    }

    //init XMPPTCPConnection
    private XMPPTCPConnection getConnection() {
        String server = "192.168.0.166"; //Server IP
        int port = 5222;
        XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
        builder.setHost(server);
        builder.setPort(port);

        builder.setServiceName("LHPC");
        builder.setCompressionEnabled(false);
        builder.setDebuggerEnabled(true);
        builder.setSendPresence(true);

        SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
        builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);

        XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());

        final FileTransferManager manager = FileTransferManager.getInstanceFor(mXMPPTCPConnection);
        manager.addFileTransferListener(new FileTransferListener() {
            @Override
            public void fileTransferRequest(FileTransferRequest request) {
                IncomingFileTransfer ift = request.accept();
                String fileName = Environment.getExternalStorageDirectory()+File.separator+request.getFileName();
                try {
                    ift.recieveFile(new File(fileName));
                } catch (SmackException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        return connection;
    }

    //Register


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_connect:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mXMPPTCPConnection = getConnection();
                        try {
                            mXMPPTCPConnection.connect();
                        } catch (SmackException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (XMPPException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.btn_register: {
                final String loginID = mEt_username.getText().toString();
                final String passwrod = mEt_password.getText().toString();
                if (loginID.equals("") || passwrod.equals("")) {
                    Toast.makeText(getApplicationContext(), "Username or Password mustm't be empty", Toast.LENGTH_LONG).show();
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (mXMPPTCPConnection.isConnected()) {
                                mXMPPTCPConnection.disconnect();
                            }
                            mXMPPTCPConnection.connect();
                            AccountManager accountManager = AccountManager.getInstance(mXMPPTCPConnection);
                            if (accountManager.supportsAccountCreation()) {
                                Map<String, String> map = new HashMap<>();
                                map.put("email", "demo@maizi.edu");
                                map.put("android", "creatUser_android");

                                accountManager.createAccount(loginID, passwrod, map);
                            }

                        } catch (SmackException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (XMPPException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            }
            case R.id.btn_login:
                final String loginID = mEt_username.getText().toString();
                final String passwrod = mEt_password.getText().toString();
                if (loginID.equals("") || passwrod.equals("")) {
                    Toast.makeText(getApplicationContext(), "Username or Password mustm't be empty", Toast.LENGTH_LONG).show();
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (mXMPPTCPConnection.isConnected()) {
                                mXMPPTCPConnection.disconnect();
                            }
                            mXMPPTCPConnection.connect();
                            mXMPPTCPConnection.login(loginID, passwrod);

                            Presence presence = new Presence(Presence.Type.available);
                            presence.setStatus("OnLine");
                            mXMPPTCPConnection.sendStanza(presence);

                            ChatManager chatManager = ChatManager.getInstanceFor(mXMPPTCPConnection);
                            chatManager.addChatListener(new ChatManagerListener() {
                                @Override
                                public void chatCreated(Chat chat, boolean createdLocally) {
                                    chat.addMessageListener(new ChatMessageListener() {
                                        @Override
                                        public void processMessage(Chat chat, Message message) {
                                            String content = message.getBody();
                                            if (content != null) {
                                                android.os.Message msg = android.os.Message.obtain();
                                                msg.what = 1;
                                                msg.obj = "Get it" + message.getBody() + " From:"
                                                        + message.getFrom();

                                                mHandler.sendMessage(msg);
                                            }
                                        }
                                    });


                                }
                            });


                        } catch (SmackException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (XMPPException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                break;
            case R.id.btn_AddFriend: {
                //TODO
                final String FriendID = edtFriendID.getText().toString();
                if (FriendID.equals("")) {
                    Toast.makeText(getApplicationContext(), "接收用户不能为空", Toast.LENGTH_LONG);
                }

                Roster roster = Roster.getInstanceFor(mXMPPTCPConnection);
                try {
                    roster.createEntry(FriendID, FriendID, null);
                } catch (SmackException.NotLoggedInException e) {
                    e.printStackTrace();
                } catch (SmackException.NoResponseException e) {
                    e.printStackTrace();
                } catch (XMPPException.XMPPErrorException e) {
                    e.printStackTrace();
                } catch (SmackException.NotConnectedException e) {
                    e.printStackTrace();
                }

                break;
            }
            case R.id.btn_sendText: {
                final String FriendID = edtFriendID.getText().toString();
                final String textMsg = edtTextMsg.getText().toString();
                if (FriendID.equals("")) {
                    Toast.makeText(getApplicationContext(), "接收用户不能为空", Toast.LENGTH_LONG);
                }
                ChatManager chatManager = ChatManager.getInstanceFor(mXMPPTCPConnection);
                Chat mChat = chatManager.createChat(FriendID);
                try {
                    mChat.sendMessage(textMsg);
                } catch (SmackException.NotConnectedException e) {
                    e.printStackTrace();
                }
                break;

            }

            case R.id.btn_sendImg: {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
                break;
            }


            case R.id.btn_sendVideo: {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
                break;
            }


            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        final String FriendID = edtFriendID.getText().toString();

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Uri selectImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);

            cursor.close();

            FileTransferManager fm = FileTransferManager.getInstanceFor(mXMPPTCPConnection);
            OutgoingFileTransfer oft = fm.createOutgoingFileTransfer(FriendID);
            File file = new File(picturePath);

            try {
                oft.sendFile(file, "See the Image");
            } catch (SmackException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == 2 && resultCode == RESULT_OK && data != null) {
            Uri selectVideo = data.getData();
            String[] filePathColumn = {MediaStore.Video.Media.DATA};

            Cursor cursor = getContentResolver().query(selectVideo, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);

            cursor.close();

            FileTransferManager fm = FileTransferManager.getInstanceFor(mXMPPTCPConnection);
            OutgoingFileTransfer oft = fm.createOutgoingFileTransfer(FriendID);
            File file = new File(picturePath);

            try {
                oft.sendFile(file, "See the Image");
            } catch (SmackException e) {
                e.printStackTrace();
            }
        }
    }
}
